<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <ul>
    <li><a href="/home">首页</a></li>
    <li><a href="/about">关于</a></li>
  </ul>

  <div id="routeView">
    <!-- 放一个代码片段 -->
  </div>

  <script>
    const routes = [
      {
        path: '/home',
        component: '<h2>首页页面内容</h2>'
      },
      {
        path: '/about',
        component: '<h3>about page</h3>'
      }
    ]

    const routeView = document.getElementById('routeView')

    window.addEventListener('DOMContentLoaded', onLoad)
    window.addEventListener('popstate', onPopState)
    
    function onLoad() {
      onPopState()
      const links = document.querySelectorAll('li a')
      links.forEach(a => {
        a.addEventListener('click', (e) =>{
          e.preventDefault()  // 阻止了a标签的默认跳转行为
          // 添加一个可以修改url又不造成页面刷新
          history.pushState(null, '', a.getAttribute('href'))
          // 映射对应的dom
          onPopState()
        })
      })
    }

    function onPopState() {
      console.log(location.pathname);
      routes.forEach(item => {
        if (item.path === location.pathname) {
          routeView.innerHTML = item.component
        }
      })
    }

  </script>
</body>
</html>